//
//  QOilRunningVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/8/13.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QOilRunningVC.h"
#import "QOilRunningCell.h"
#import "QOilingModel.h"
#import "QGunModel.h"
#import "UICountingLabel.h"
#import "QOilNumberModel.h"
@interface QOilRunningVC ()<UITableViewDelegate,UITableViewDataSource>
{
    NSTimer *_timer;//计时器
    
    CGFloat speed;//速度
    
    CGFloat time;//时间
    
    BOOL _first;//是否是第一次

}

@property (weak, nonatomic) IBOutlet UIButton *speedBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UICountingLabel *moneylabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *quantitylabel;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *gunArr;
@end

@implementation QOilRunningVC

- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}

- (void)dealloc{
    [_timer invalidate];
    _timer = nil;
    CLog(@"释放了");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];

    [_timer invalidate];
    _timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"nav_whiteBack"];
    button.frame = CGRectMake(5, 30, 50, image.size.height);
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"nav_grayBack"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];
    self.title = @"加油机详情";
    self.view.backgroundColor = [QColorUtility colorWithHexString:@"#373e47"];
    self.moneylabel.font = [UIFont fontWithName:@"DBLCDTempBlack" size:34];
    self.quantitylabel.font = [UIFont fontWithName:@"DBLCDTempBlack" size:34];

    _quantitylabel.format = @"%.2f";
    _moneylabel.format = @"%.2f";
    
    _moneylabel.method = UILabelCountingMethodLinear;
    _quantitylabel.method = UILabelCountingMethodLinear;
    
    [QViewUtility setupNavigationBarBackForController:self backSelector:@selector(back)];
    [self requestData];
    _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
    _first = YES;
    speed = 5;//1秒每升

    [self createUi];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createUi{
    self.tableView.delegate =self;
    self.tableView.dataSource =self;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QOilRunningCell" bundle:nil] forCellReuseIdentifier:@"QOilRunningCell"];

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _gunArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QOilRunningCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QOilRunningCell"];
    cell.backgroundColor = [UIColor clearColor];
    cell.gunModel = [_gunArr objectAtIndex:indexPath.row];

    return cell;
}

- (void)requestData{
    NSString * url =[QParamService urlWithAction:@"getCarRealtimeComeonData"];
    NSDictionary * para = [QParamService getCarRealtimeComeonDataWithOrderId:self.orderId];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        QBaseModel * baseModel = [QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            QOilingModel * model = [QOilingModel objectFromDict:baseModel.items];
            
            if (model.list.count == 0) {
                return ;
                
            }
            if (model.list.count == self.dataArray.count) {
                return;
            }else{
                
            }
            
            if (model.list.count) {
                
                self.dataArray = model.list;
                [self OilOfRunning:self.dataArray];
                self.gunArr = [QGunModel mj_objectArrayWithKeyValuesArray:model.hangGunList];
                [_tableView reloadData];
            }
        }else{
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
        
    }];
}

- (void)OilOfRunning:(NSMutableArray *)arr{
    if (arr.count == 0) {
        return;
    }
    
    
    if (_first == YES) {
        QOilNumberModel *model = [arr lastObject];
        
        time = model.realTimeNumber/speed;
        
        //timelab.text = [NSString stringWithFormat:@"加油时间总计%.f秒",time];
        
        if (time>120) {
            
            _quantitylabel.speed = NO;
            _moneylabel.speed = NO;
            
            [_quantitylabel countFrom:0.00 to:model.realTimeNumber withDuration:time];
            
            [_moneylabel countFrom:0.00 to:model.realTimePrice withDuration:time];
            
            _first = NO;
            
        }else{
            [QViewUtility showToastToView:[UIApplication sharedApplication].delegate.window message:@"数据同步中"];
        }
        
        if (time<300) {
            _speedBtn.hidden = YES;
        }else{
            _speedBtn.hidden = NO;
        }
        
    
    }else{
        
        QOilNumberModel * model1 = [arr lastObject];
        
        time = (model1.realTimeNumber - [_quantitylabel.text floatValue])/speed;
        
        [_quantitylabel countFromCurrentValueTo:model1.realTimeNumber withDuration:time];
        
        [_moneylabel countFromCurrentValueTo:model1.realTimePrice withDuration:time];
        
        
    }

}

- (IBAction)speedAction:(id)sender {
    _quantitylabel.speed = YES;
    _moneylabel.speed = YES;

}

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)gunArr{
    if (!_gunArr) {
        _gunArr = [NSMutableArray array];
    }
    return _gunArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
